<style lang="less">
	.img-container{
		background-color: white;
    text-align: left;
	}
  .van-uploader__preview-delete {
    top: 0!important;
  }
  .van-uploader__preview{
    margin-right: 0.35rem!important;
  }
</style>
<template>
	<div class="img-container">
		<van-uploader :max-count="maxCount" preview-size="1.3rem" v-model="fileList" multiple :after-read="afterRead" :before-delete="del"/>
	</div>
</template>
<script>
  import {uploadImg, delImg} from '../../api/upload';
  import lrz from 'lrz'
  import Vue from 'vue';
  import {Uploader} from 'vant';

  Vue.use(Uploader);
  export default {
    name: 'upload',
    props: {
      value: {
        type: Array, default: function () {
          return []
        }
      },
      maxCount:{type:Number,default:99}
    },
    watch: {
      value: {
        immediate: true,
        handler(fileList) {
          let vm = this;
          this.fileList = fileList.map(v => {
            v.url = vm.GLOBAL.getUrl(v.name, true);
            return v;
          });
        }
      },
      fileList: {
        handler(fileList) {

          if (fileList.length !== this.value.length) {
            this.$emit('input', this.fileList)
          }
        }
      }
    },
    data() {
      return {
        fileList: []
      }
    },
    methods: {
      afterRead(file) {
        if (file instanceof Array) {
          file.forEach(v => {
            this.compress(v);
          })
        } else {
          this.compress(file);
        }
        this.$emit('input', this.fileList)
      },
      async compress(file) {
        let done = false;
        await lrz(file.file, {width: 600})
          .then(function (rst) {
            let params = new FormData();
            params.append('file', rst.file, file.file.name);
            // 处理成功会执行
            uploadImg(params).then(rep => {
              file.name = rep.data.data.name;
            });
            done = true;
          })
          .catch(function (err) {
            // 处理失败会执行
          })
          .always(function () {
            // 不管是成功失败，都会执行
          });
        return done;
      },
      del(file) {
        if (file.name !== undefined) {
          //这里只删除本次上传的，不删除之前已经保存过的图,也只是尽量删除了，为云存储省一点空间，毕竟都是钱
          if (file.file !== undefined) {
            delImg(file.name)
          }
        }
        return true;
      }
    }
  }

</script>